from functools import wraps
from flask_jwt_extended import get_jwt_identity
from app.models import User, ServerMember, ChannelPermissions


def user_required(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        user_id = get_jwt_identity()
        if not user_id:
            return {'message': 'User authentication required'}, 401
        return fn(*args, **kwargs)

    return wrapper


def channel_permission_required(permission_name):
    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            user_id = get_jwt_identity()
            channel_id = kwargs.get('channel_id')

            # 检查用户是否有该频道的特定权限
            permission = ChannelPermissions.query.filter_by(
                channel_id=channel_id,
                user_id=user_id
            ).first()

            if not permission or not getattr(permission, permission_name, False):
                return {'message': f'Channel {permission_name} permission required'}, 403

            return fn(*args, **kwargs)

        return wrapper

    return decorator